﻿using Apps.Excel;
using Microsoft.AspNetCore.Mvc;

namespace WebApplication2.Utility
{
    public class ExcelResult : IActionResult
    {
        private string _ExcelName;
        private List<ExcelDataResource> _ExcelDataResources;

        /// <summary>
        /// 如果没有时间就默认以当前时间为文件名称
        /// </summary>
        public ExcelResult(List<ExcelDataResource> excelDataResources):this(DateTime.Now.ToString("yyyyMMddHHmmssffffff"),excelDataResources)
        {
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="excelName">文件名称</param>
        /// <param name="excelDataResources">数据源</param>
        public ExcelResult(string excelName,List<ExcelDataResource> excelDataResources)
        {
            this._ExcelName = excelName;
            this._ExcelDataResources = excelDataResources;
        }


        public Task ExecuteResultAsync(ActionContext context)
        {
            //return Task.Run(() =>
            //{

            //context.HttpContext.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            //context.HttpContext.Response.Headers.Add("Content-Disposition", $"attachment;filename={_ExcelName}.xls");

            context.HttpContext.Response.ContentType = "application/vnd.ms-excel";
            context.HttpContext.Response.Headers.Add("Content-Disposition", $"attachment;filename={_ExcelName}.xls");

            byte[] bt = ExcelOperationHelper.ToExcelByteArray(_ExcelDataResources);
            context.HttpContext.Response.BodyWriter.WriteAsync(bt);




            //MemoryStream memoryStream = ExcelOperationHelper.ExcelToMemoryStream(_ExcelDataResources, _ExcelName);
            //byte[] butte = memoryStream.ToArray();
            //memoryStream.Write(butte);


            //using (FileStream fileStream = new FileStream("D:\\ZXWork\\Advanced15\\NPOI课件\\TestInfo.xlsx", FileMode.Open))
            //{
            //    byte[] bytes = new byte[fileStream.Length];
            //    fileStream.Read(bytes, 0, bytes.Length);
            //    fileStream.Seek(0, SeekOrigin.Begin);
            //    context.HttpContext.Response.BodyWriter.WriteAsync(bytes);
            //}

            //});

            return Task.CompletedTask;

        }
    }
}
